"use strict";

app.directive('crop', ['CropService', function (CropService) {
    return {
        restrict: 'EA',
        scope: {
            out: "=?",
            src: "=?",
            image: "=?",
            ratio: "=?",
            width: "=?",
            maxWidth: "=?",
            canvasWidth: "=?"
        },
        template: '<canvas class="crop"></canvas>',
        link: function (scope, iElement, iAttrs) {
            var canvas = iElement.find("canvas");

            var options = {
                ratio: scope.ratio,
                width: scope.width,
                maxWidth: scope.maxWidth,
                image: scope.image,
            };

            var cropService = new CropService(canvas[0], options);

            cropService.oncrop = function (dataUrl) {
                scope.out = dataUrl;
                console.log('dataUrl', dataUrl);
            };

            scope.$on('crop', function () {
                cropService.crop();
            });
            scope.$on('rotateRight', function () {
                cropService.rotateRight();
            });
            scope.$on('rotateLeft', function () {
                cropService.rotateLeft();
            });

            scope.$on('$destroy', function () {
                cropService.dispose();
            });
        }
    };
} ]);

app.directive('fileInput', ["$parse", function ($parse) {
    return {
        restrict: "EA",
        template: "<input type='file' style='display:none'/>",
        replace: true,
        link: function (scope, element, attrs) {

            var modelGet = $parse("file");
            var modelSet = modelGet.assign;
            var onChange = $parse(attrs.onChange);

            var updateModel = function () {
                scope.$apply(function () {
                    modelSet(scope, element[0].files[0]);
                    element[0].value = null; //clear input
                    onChange(scope);
                });
            };

            element.bind('change', updateModel);
        }
    };
} ]);

app.directive('buttonCrop', ["$mdDialog", "$timeout", "$compile", "FileReader", "imageService", function ($mdDialog, $timeout, $compile, fileReader, imageService) {

    function DialogController($scope, $mdDialog, image, ratio, width, maxWidth, out) {
        $scope.original = image;
        $scope.cropped = out;
        $scope.ratio = ratio;
        $scope.width = width;
        $scope.maxWidth = maxWidth;
        $scope.rotateRight = function () {
            $scope.$broadcast('rotateRight');
        };
        $scope.rotateLeft = function () {
            $scope.$broadcast('rotateLeft');
        };
        $scope.hide = function () {
            $mdDialog.hide();
        };

        $scope.cancel = function () {
            $mdDialog.cancel();
        };

        $scope.answer = function (answer) {
            $scope.$watch('cropped', function (newValue) {
                if (!newValue) return;
                $mdDialog.hide(newValue);
            });
            $scope.$broadcast('crop');
        };
    }

    return {
        restrict: 'EA',
        scope: {
            out: "=?",
            src: "=",
            ratio: "=?",
            width: "=?",
            maxWidth: "=?",
            progress: "=?",
            select: "&?"
        },
        link: function (scope, element, attrs, ctrl) {
            var el = $compile('<file-input on-change="readFile()"></file-input>')(scope);
            var input = el[0];
            angular.element(element).append(el);

            element.on("click", function (event) {
                scope.$apply(function () {
                    scope.progress = 0;
                });
                input.click();
            });

            scope.readFile = function () {
                fileReader.readAsDataUrl(scope.file, scope).then(function (result) {
                    imageService.create(result).then(function (image) {
                        scope.open(image);
                    }, function (error) {
                        //console.log("fileProgress error", error);
                    }, function (notify) {
                        //console.log("fileProgress notify", notify);
                    });
                });
            };

            scope.$on("fileProgress", function (e, progress) {
                scope.$apply(function () {
                    scope.progress = (progress.loaded / progress.total) * 100;
                    //console.log("fileProgress", scope.progress);
                });
            });

            scope.open = function (data) {
                $mdDialog.show({
                    clickOutsideToClose: false,
                    controller: DialogController,
                    templateUrl: '/pro/partials/editors/crop.html',
                    locals: {
                        image: data,
                        ratio: scope.ratio,
                        width: scope.width,
                        maxWidth: scope.maxWidth,
                        out: scope.out
                    }
                }).then(function (result) {
                    scope.out = result;
                    if (scope.select) scope.select({ "$image": result });
                }, function () {
                    scope.out = scope.image;
                });
            };
        }
    };
} ]);
